<script setup>
import {ref} from "vue";
import defaultUrl from '@/assets/defaultAvatar.png'

// 当前日期
const currentDate = ref(new Date())
// 获取用户信息
import {useUserInfoStore} from "@/stores/userInfo.js";
import {useTokenStore} from "@/stores/token.js"
import {updateUserInfoService, userInfoService, uploadAvatarService} from "@/api/user.js";
import {ElMessage} from "element-plus";
import {Back, Upload} from "@element-plus/icons-vue";

const userInfoStore = useUserInfoStore()
const tokenStore = useTokenStore()
const userInfo = ref()
const uploadRef = ref()
const imgUrl = ref(userInfoStore.userInfo.avatarUrl ? userInfoStore.userInfo.avatarUrl : defaultUrl)

// 折叠面板生效name
const activeNames = ref('off')
const getUserInfo = () => {
  userInfo.value = userInfoStore.userInfo
}

// 调用
getUserInfo()

const newUserInfo = ref({
  userId: '',
  username: '',
  email: '',
})

const rules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 16, message: '长度在3~16个字符', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {type: 'email', message: '邮箱格式不正确', trigger: "blur"}
  ]
}

// 更新用户信息
const updateUserInfo = async () => {
  newUserInfo.value.userId = userInfo.value.userId
  let result = await updateUserInfoService(newUserInfo.value)

  ElMessage.success(result.message ? result.message : 'update success')
  // 关闭collapse
  activeNames.value = 'off'
  // 重新获取用户信息
  let userInfoBack = await userInfoService()
  // 更新Store里的用户信息
  userInfoStore.setUserInfo(userInfoBack.data)
  // 清空model
  newUserInfo.value = {
    userId: '',
    username: '',
    email: ''
  }
  // 重新渲染界面
  getUserInfo()
}

const centerDialogVisible = ref(false)

// 上传头像
const uploadAvatar = async () => {
  if (!imgUrl.value) ElMessage.error('未选择图片')
  else {
    let result = await uploadAvatarService(imgUrl.value)
    ElMessage.success(result.message ? result.message : '上传成功')
    userInfoStore.userInfo.avatarUrl = imgUrl.value
  }
}
const uploadSuccess = (val) => {
  imgUrl.value = val.data
}
</script>

<template>
  <el-card class="page-container">
    <el-row justify="space-between">
      <el-col :span="14">
        <el-card>
          <div class="avatar-box">
            <el-avatar v-if="imgUrl" @click="centerDialogVisible=true" :size="100" :src="imgUrl"/>
            <el-avatar v-else @click="centerDialogVisible=true" :size="100" :src="defaultUrl"/>
          </div>
          <br>
          <br>
          <el-text class="mx-1" size="large" type="info">username:</el-text>
          <br>
          <br>
          <el-text class="mx-1" size="large">{{ userInfo.username }}</el-text>
          <br>
          <br>
          <el-text class="mx-1" size="large" type="info">email:</el-text>
          <br>
          <br>
          <el-text class="mx-1" size="large">{{ userInfo.email }}</el-text>
          <br>
          <br>
          <!-- 更新信息 -->
          <div class="update-collapse">
            <el-collapse v-model="activeNames">
              <el-collapse-item title="Update UserInfo" name="on">
                <el-form
                    :label-position="'left'"
                    label-width="200px"
                    :model="newUserInfo"
                    :rules="rules"
                    style="max-width: 460px"
                >
                  <el-form-item label="new username:" prop="username">
                    <el-input v-model="newUserInfo.username"/>
                  </el-form-item>
                  <el-form-item label="new email:" prop="email">
                    <el-input v-model="newUserInfo.email"/>
                  </el-form-item>
                  <el-button type="primary" round @click="updateUserInfo">Submit</el-button>
                </el-form>
              </el-collapse-item>
            </el-collapse>
          </div>

          <!-- 上传头像 -->
          <el-dialog v-model="centerDialogVisible" title="Upload Avatar" width="500" center>
            <div style="justify-content: center;display: flex">
              <el-upload ref="uploadRef" class="avatar-uploader" :show-file-list="false" :auto-upload="true"
                         action="/api/upload" name="file" :headers="{ 'Authorization': tokenStore.token }"
                         :on-success="uploadSuccess">
                <el-avatar v-if="imgUrl" :src="imgUrl" :size="'large'" alt=""/>
                <el-avatar v-else :src="defaultUrl" :size="'large'" alt=""/>
              </el-upload>
            </div>

            <template #footer>
              <div class="dialog-footer">
                <el-button type="info" :icon="Back" size="large" @click="centerDialogVisible = false">
                  Cancel
                </el-button>
                <el-button type="success" :icon="Upload" size="large" @click="uploadAvatar">
                  Upload
                </el-button>
              </div>
            </template>
          </el-dialog>

        </el-card>

      </el-col>
      <el-col :span="8">
        <el-card>
          <el-calendar v-model="currentDate"/>
        </el-card>
      </el-col>

    </el-row>
  </el-card>
</template>

<style scoped lang="scss">

.page-container {
  min-height: 100%;
  min-width: 100%;

  .avatar-box {
    display: flex;
    justify-content: center;

    .el-avatar {
      cursor: pointer;
      transition: all 0.4s;

      &:hover {
        box-shadow: var(--el-box-shadow);
        border: 1px solid var(--el-color-primary);
      }
    }
  }


}

.item {
  padding: 18px 0;
}

</style>